package com.zhongshengnetwork.rightbe.letter.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.thinkcool.circletextimageview.CircleTextImageView;
import com.zhongshengnetwork.rightbe.Adv.model.AdvertUtils;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.Constant.LetterConstant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppUtils;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.CircleTransform;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.DateUtil;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.customview.MutiColorTextView;
import com.zhongshengnetwork.rightbe.common.customview.PublishSelectPicPopupWindow;
import com.zhongshengnetwork.rightbe.dbmodel.LetterdbModel;
import com.zhongshengnetwork.rightbe.dbservice.LetterdbService;
import com.zhongshengnetwork.rightbe.lang.viewmodel.LetterViewModel;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

////import cn.jiguang.analytics.android.api.JAnalyticsInterface;

public class LetterConversationActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener{

    private MyAdapter adapter;
    private List<LetterdbModel> list = null;
    private ListView listview;
    private TopBarView topbar;
    private PublishSelectPicPopupWindow menuWindow;
    private CircleTextImageView mNewText;
    private int opPosition = 1;

    private Timer mTimer = null;
    private TimerTask mTimerTask = null;
    private int timeCount = 0;
    private static int delay = 2000;  //2s
    private static int period = 2000;  //2s
    private boolean timeFlag = false;
    private boolean chatFlag = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_letter_conversation);
        topbar = (TopBarView)findViewById(R.id.topbar);
        if (SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(LetterConstant.ReceivingKey, false) == true){
            topbar.getTitleView().setText("接收中...");
        }else {
            topbar.getTitleView().setText("私信");
        }
        topbar.getRightView().setVisibility(View.GONE);
        topbar.setClickListener(this);
        topbar.getRightView().setImageResource(R.drawable.settings);
        topbar.getRightView().setVisibility(View.VISIBLE);
        topbar.getRightView().setClickable(true);
        topbar.getRightView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LetterConversationActivity.this, LetterSettingActivity.class);
                startActivity(intent);
            }
        });
        if (list == null){
            list = new ArrayList<LetterdbModel>();
        }
        listview=(ListView) findViewById(R.id.message_listview);
        adapter=new MyAdapter();
        listview.setAdapter(adapter);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Log.e("TAG", "position="+position);
                if (position < list.size()){
                    LetterdbModel model = list.get(position);
                    Intent intent = new Intent(LetterConversationActivity.this, ChatViewActivity.class);
                    Bundle bundle=new Bundle();
                    bundle.putSerializable("model", model);//序列化
                    bundle.putInt("newCount",model.getUnReadCount());
                    intent.putExtras(bundle);//发送数据
                    startActivity(intent);
                    model.setUnReadCount(0);
                    LetterdbService.changeToReadState(model.getUserid(), model.getFromuserid());
                    LetterdbModel m = LetterdbService.getByMsgId(model.getUserid()+model.getFromuserid());
                    if (m != null){
                        m.setUnReadCount(0);
                        LetterdbService.saveOrUpdate(m);
                    }
                    adapter.notifyDataSetChanged();
                    Intent mIntent = new Intent(BroadcastDefine.Update_MsgCount_Action);
                    //发送广播
                    CustomApplication.mContext.sendBroadcast(mIntent);
                    chatFlag = true;
                }


            }
        });
        listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                opPosition = position;
                List<String> names = new ArrayList<String>();
                names.add("删除");
                names.add("取消");
                menuWindow = new PublishSelectPicPopupWindow(LetterConversationActivity.this,itemsOnClick,names);
                // 显示窗口
                menuWindow.showAtLocation(view,
                        Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                return true;
            }
        });
        getData();
    }


    @Override
    protected void onResume() {
        super.onResume();
        if(AppUtils.getInstance().isUserAgreeStatus() == false){
    return;
}
////JAnalyticsInterface.onPageStart(getApplicationContext(),this.getClass().getCanonicalName());
        startTimer();
    }


    @Override
    protected void onPause() {
        super.onPause();
        if(AppUtils.getInstance().isUserAgreeStatus() == false){
    return;
}
////JAnalyticsInterface.onPageEnd(getApplicationContext(),this.getClass().getCanonicalName());
        stopTimer();
    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        //Toast.makeText(LoginActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();
        finish();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    private void getData(){
        new Thread(){
            @Override
            public void run() {
                super.run();
                final List<LetterdbModel> l = LetterdbService.getConversation(CustomApplication.loginModel.getUid(),0,1000);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (list == null){
                            list = new ArrayList<LetterdbModel>();
                        }
                        list.clear();
                        if (l != null && l.size() > 0){
                            Log.e("TAG","私信内容大小="+l.size());
                            list.addAll(l);
                            LetterdbModel model = list.get(0);
                            Log.e("TAG","私信内容="+model.getContent());
                        }else {
                            Log.e("TAG","没有私信内容");
                        }
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        }.start();
    }

    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }
        @Override
        public boolean isEnabled(int position) {
            // TODO Auto-generated method stub
            return super.isEnabled(position);
        }

        /**
         * @param position
         * @param convertView
         * @param parent
         * @return
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            View view=convertView;
            LetterdbModel conversationModel = list.get(position);
            view=LayoutInflater.from(CustomApplication.mContext).inflate(R.layout.message_list_item, null);
            ImageView header = (ImageView) view.findViewById(R.id.message_list_item_header);
            RelativeLayout group = (RelativeLayout) view.findViewById(R.id.message_list_item_group);
            ImageView groupHeader = (ImageView) view.findViewById(R.id.message_list_item_groupheader);
            CircleTextImageView newtext = (CircleTextImageView) view.findViewById(R.id.message_list_item_newcount);
            TextView nickname = (TextView) view.findViewById(R.id.message_list_item_nickname);
            TextView time = (TextView) view.findViewById(R.id.message_list_item_time);
            MutiColorTextView content = (MutiColorTextView) view.findViewById(R.id.message_list_item_content);
            nickname.setText(conversationModel.getNickname());
            Log.e("TAG","position="+position);
            if (conversationModel.isCancel() == true || conversationModel.getType() == LetterConstant.sx_timeMsg){
                content.setText(CommonUtils.formatString(conversationModel.getExtra()));
            }else {
                if (conversationModel.getType() == LetterConstant.sx_textMsg){
                    content.setText(conversationModel.getContent());
                } else {
                    content.setText("当前版本不支持该类型消息，请升级到最新版本查看");
                }
            }

            time.setText(DateUtil.getChatDate(conversationModel.getTime()));
            if (conversationModel.getUnReadCount() > 0){
                newtext.setText(conversationModel.getUnReadCount()+"");
                newtext.setVisibility(View.VISIBLE);
            }else {
                newtext.setText("");
                newtext.setVisibility(View.INVISIBLE);
            }

            header.setVisibility(View.VISIBLE);
            group.setVisibility(View.INVISIBLE);
            Glide.with(CustomApplication.mContext).load(conversationModel.getHeader()).transform(new CircleTransform(CustomApplication.mContext)).dontAnimate().into(header);

            TextView clicktext=(TextView) view.findViewById(R.id.message_list_item_clicktext);
            clicktext.setVisibility(View.INVISIBLE);
            return view;
        }
    }

    // 为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.first_button://删除
                    if (list != null && list.size() > 0 && opPosition >= 0 && list.size() > opPosition){
                        final LetterdbModel conversationModel = list.get(opPosition);
                        LetterdbService.deleteByMsgId(conversationModel.getUserid()+conversationModel.getFromuserid());
                        list.remove(conversationModel);
                        adapter.notifyDataSetChanged();
                    }
                    break;
                default:
                    break;
            }

        }
    };

    private void startTimer(){

        if (timeFlag == true){
            return;
        }

        if (mTimer == null) {
            mTimer = new Timer();
        }

        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    //定时事件到了
                    Log.e("TAG", "定时时间到："+SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(LetterConstant.ReceivingKey, false));
                    boolean isReceive = SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(LetterConstant.ReceivingKey, false);
                    if (isReceive == true || chatFlag == true){
                        chatFlag = false;
                        if (isReceive == true){
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    topbar.getTitleView().setText("接收中...");
                                }
                            });
                        }else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    topbar.getTitleView().setText("私信");
                                }
                            });
                        }
                        getData();
                    }else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                topbar.getTitleView().setText("私信");
                            }
                        });
                    }
                }
            };
        }

        if(mTimer != null && mTimerTask != null ){
            mTimer.schedule(mTimerTask, delay, period);
            timeFlag = true;
        }

    }

    private void stopTimer(){
        if (mTimer != null) {
            timeCount = 0;
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
        timeCount = 0;
        timeFlag = false;
    }

}
